<?php

namespace App\Service\OpenShop;

use App\Enums\Contract\ContractErrCode;
use App\Enums\Fee\FeeEnum;
use App\Enums\OpenShop\BaseErrorCode;
use App\Enums\OpenShop\InvestmentPromotion\ContractStatusEnum;
use App\Enums\OpenShop\InvestmentPromotion\ErrCode;
use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserContractEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserOrderEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Enums\Workflow\WorkflowEnum;
use App\Error\BaseError;
use App\Error\OpenShop\RenewError;
use App\Events\OpenShop\UserContractCreatedEvent;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Exceptions\Custom\ResponseHttpException;
use App\Exceptions\KfHttpResponseException;
use App\Http\Resources\OpenShop\InvestmentPromotion\ContractTemplateListResource;
use App\Http\Resources\OpenShop\InvestmentPromotion\OrderDetailResource;
use App\Http\Resources\OpenShop\InvestmentPromotion\UserContractResource;
use App\Library\FeiShu\SendFs;
use App\Library\Rms\RmsShopApi;
use App\Models\BaseModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderLogModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserExtContractModel;
use App\Models\Workflow\WorkflowOrderModel;
use App\Models\Workflow\WorkflowOrderNodeModel;
use App\Service\BaseService;
use App\Service\OpenShop\Feishu\MissionTemplateService;
use App\Service\OpenShop\Feishu\UserExtContractService;
use App\Service\OpenShop\Import\HistoryOrder\HistoryOrderParam;
use App\Support\ChangeSupport;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Kuafu\GeneralFs\BuildFs;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use function Symfony\Component\Translation\t;

/**
 * @author Green Leaf <786407418@qq.com>
 */
class UserContractService extends BaseService
{

    /**
     * 模版列表
     *
     * @param $mode
     * @return array
     */
    public static function templateList(int $mode, int $contractType): array
    {
        return [
            'templateList' => ContractTemplateListResource::collection(
                OpenShopContractTemplateModel::query()
                                             ->where('isShow', OpenShopContractTemplateModel::IS_SHOW_1)
                                             ->where('mode', $mode)
                                             ->whereJsonContains('contractTypeV2', [$contractType])
                                             ->where("startTime", "<", time())
                                             ->where("endTime", ">", time())
                                             ->orderBy(
                                                 "createdAt",
                                                 "desc"
                                             )->get()
            )
        ];
    }

    public static function checkProvideShopCode(
        int $shopCode,
        int $policyTemplateId,
        string $orderNo = '',
        bool $rmsCheckShopCode = false
    ) {
        if ($shopCode) {
            $shopCount = OpenShopContractTemplateModel::query()->where('id', $policyTemplateId)->value('shopCount');
            if ($shopCount != 1) {
                throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_SHOP_NUM_PROVIDE_CODE));
            }

            // openShop已有门店校验
            $checkOpenShop = OpenShopSignOrderModel::query()
                                                   ->when($orderNo, function ($query) use ($orderNo) {
                                                       $query->where('orderNo', '!=', $orderNo);
                                                   })
                                                   ->where('shopCode', $shopCode)
                                                   ->where('status', SignOrderEnum::ORDER_STATUS_OK)
                                                   ->selectRaw(1)
                                                   ->count();
            if ($checkOpenShop) {
                throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_SHOP_CODE_IN_OPEN_SHOP));
            }

            // 未支付的订单校验
            $checkOpenShop = OpenShopSignOrderModel::query()
                                                   ->when($orderNo, function ($query) use ($orderNo) {
                                                       $query->where('orderNo', '!=', $orderNo);
                                                   })
                                                   ->where('provideShopCode', $shopCode)
                                                   ->where('step', '<', SignOrderEnum::STEP_4)
                                                   ->where('status', SignOrderEnum::ORDER_STATUS_OK)
                                                   ->selectRaw(1)
                                                   ->count();
            if ($checkOpenShop) {
                throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_SHOP_CODE_OCC_SIGN_ORDER));
            }

            // rms校验
            $checkRms = (new RmsShopApi())->checkOpenShopCode($shopCode);
            if (!$checkRms['code']) {
                $checkRmsMsg = $checkRms['msg'] ?? '';

                // 检查门店信息 - 已存在，则直接返回
                $rmsShopInfo = (new RmsShopApi())->getShopByCode($shopCode);
                if ($rmsShopInfo['code'] == 1) {

                    // rms已建店
                    SendFs::newRobot(SendFs::ROBOT_OPEN_SHOP)
                          ->setTitleContent("新关联rms已有门店",
                              "订单号：{$orderNo} 门店编号：{$shopCode}，请关注", '5dd87136')
                          ->send();
                    return;
                }

//                if ($rmsCheckShopCode) {
//                    throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_SHOP_CODE,
//                        $checkRmsMsg));
//                }
//
//                if (!HistoryOrderParam::$importOrderMode) {
//                    SendFs::newRobot(SendFs::ROBOT_OPEN_SHOP)
//                          ->setTitleContent("开店设置的门店编号与原定逻辑冲突，请人工核实",
//                              "异常信息：{$checkRmsMsg} 订单号：{$orderNo} 门店编号：{$shopCode}", '5dd87136')
//                          ->send();
//                }

                if (!HistoryOrderParam::$importOrderMode) {
                    throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_SHOP_CODE,
                        $checkRmsMsg));
                }
            }
        }
    }

    /**
     * @param object $rmsUser
     * @param array $params
     * @return array[]
     */
    public static function insert(
        object $rmsUser,
        array $params,
        bool $rmsCheckShopCode = false,
        bool $needGen = true
    ): array {
        // 校验shopCode
        $shopCode         = (int)($params['provideShopCode'] ?? 0);
        $policyTemplateId = (int)($params['policyTemplateId'] ?? 0);

        self::checkProvideShopCode($shopCode, $policyTemplateId, $params["orderNo"], $rmsCheckShopCode);

        unset($params['provideShopCode']);

        // 应付加盟费
        $template = OpenShopContractTemplateModel::query()->find($policyTemplateId);
        if (!$template) {
            throw new CustomHttpResponseException(
                ErrCode::errCodeTrans(ErrCode::CODE_ERR_CONTRACT_TEMPLATE)
            );
        }

        $insertUserContract = $params;

        try {
            DB::beginTransaction();

            // 注意： 加盟政策信息按照数据库为准
            $insertUserContract              = self::updateContractTemplateMsg($insertUserContract, $template->toArray());
            // 开始时间以提交为准
            $insertUserContract['endTime']   = strtotime("+3 years", $insertUserContract['startTime']) - 86400;

            $userContractId = OpenShopUserContractModel::query()->insertGetId(array_merge($insertUserContract, [
                "createdByUid" => $rmsUser->id,
                "createdAt"    => time()
            ]));

            //更新订单表金额&步骤
            OpenShopSignOrderModel::query()->where("orderNo", $params["orderNo"])->update([
                "shouldPayPrice"  => self::getShouldPayPrice($template),
                "step"            => UserOrderEnum::STEP_GENERATE_CONTRACT,
                "updatedAt"       => time(),
                "updatedByUid"    => $rmsUser->id,
                'provideShopCode' => $shopCode,
            ]);

            OpenShopMainProcessModel::updateNowStepStatus($params['orderNo'], MissionTemplateEnum::STEP_STATUS_1);

            DB::commit();
            if ($needGen) {
                event(new UserContractCreatedEvent($userContractId, $rmsUser->id));
            }
            return [
                "orderInfo" => $params["orderNo"],
                "userInfo"  => [
                    "investmentManagerId"   => $rmsUser->id,
                    "investmentManagerName" => $rmsUser->username
                ]
            ];
        } catch (Exception $e) {
            DB::rollBack();
            throw new CustomHttpResponseException(
                ErrCode::errCodeTrans(BaseErrorCode::BASE_CODE_INSERT_FAIL),
                $e
            );
        }
    }

    /**
     * 获取shouldPayPrice
     * @param OpenShopContractTemplateModel $template
     * @return int
     */
    public static function getShouldPayPrice(OpenShopContractTemplateModel $template): int
    {
        $shouldPayPrice = 0;
        foreach ($template->toArray() as $field => $v) {
            if (in_array($field, OpenShopSignOrderModel::ORDER_SHOULD_PRICE_FROM)) {
                $shouldPayPrice += $v;
            }
        }

        $shopCount = $template->shopCount;
        if ($shopCount <= 0) {
            throw new CustomHttpResponseException(
                ErrCode::errCodeTrans(ErrCode::CODE_ERR_TEMPLATE_SHOP_COUNT)
            );
        }

        // 订单金额 = 合同金额 * 店铺数量
        /**
         * 存储逻辑：
         * 1. 主单 - 金额 = 1店 + 定金 * shopCount
         * 2. 子单 - 金额 = 1店尾款
         * 3. 子单付了尾款，就把金额减少。加到主单上去
         *
         * 显示调整：
         * 1. 主单 - 金额 = 加盟合计金额 / 实付金额
         * 2. 子单 - 金额 = 无脑显示 0 / 0
         */

        // 主单应付

        // 定金模式 = 单店
        if ($template->mode == OpenShopContractTemplateModel::MODE_3) {
            $shouldPayPrice += ($template->depositAmount * ($shopCount - 1));
        } else {
            $shouldPayPrice *= $template->shopCount;
        }

        return $shouldPayPrice;
    }

    /**
     * @param int $uid
     * @param array $params
     * @param string $orderNo
     */
    public static function update(int $uid, array $params, string $orderNo)
    {
//        $eventManager = new OrderEditedEventManager($orderNo, $uid);
//        $eventManager->recordOriginals();
        // 校验shopCode
        $shopCode         = (int)($params['provideShopCode'] ?? 0);
        $policyTemplateId = (int)($params['policyTemplateId'] ?? 0);

        // 加盟政策信息
        $template = OpenShopContractTemplateModel::query()->find($policyTemplateId);
        if (!$template) {
            throw new CustomHttpResponseException(
                ErrCode::errCodeTrans(ErrCode::CODE_ERR_CONTRACT_TEMPLATE)
            );
        }

        $orderDetail = OpenShopSignOrderModel::query()->where("orderNo", $orderNo)->first();
        if (!$orderDetail->shopCode) {
            self::checkProvideShopCode($shopCode, $policyTemplateId, $orderNo);
        }

        try {
            DB::beginTransaction();
            $common = ["updatedAt" => time(), "updatedByUid" => $uid];

            $updateData = collect($params)->merge($common)->except('provideShopCode');
            // 获取原来的加盟政策模版,只有 泛微 导入的模版的合同才能更新原来的订单信息
            $orgContract = OpenShopUserContractModel::query()->where('orderNo', $orderNo)->first();
            if ($orderDetail->step >= UserOrderEnum::STEP_PART_PAID || $orgContract->policyTemplateId && $orgContract->policyTemplateId == 27) {
                //订单步骤到部分支付以后不能修改金额数据
                $updateData = $updateData->except(OpenShopSignOrderModel::ORDER_SHOULD_PRICE_FROM);
            } else {
                OpenShopSignOrderModel::query()->where("orderNo", $orderNo)->update(array_merge([
                    "shouldPayPrice"  => self::getShouldPayPrice($template),
                    'provideShopCode' => $shopCode,
                ], $common));
            }

            // 手动修复金额问题
            $updateDataUserContract = $updateData->toArray();
//            foreach (OpenShopSignOrderModel::ORDER_SHOULD_PRICE_FROM as $priceOne) {
//                $updateDataUserContract[$priceOne] = (int)($updateDataUserContract[$priceOne] / $updateDataUserContract['shopCount']);
//            }
//            $updateDataUserContract['managementCostEveryYear'] = (int)($updateDataUserContract['managementCostEveryYear'] / $updateDataUserContract['shopCount']);

            // 覆盖加盟政策合同信息 : 已支付状态不可修改
            $updateDataUserContract = self::updateContractTemplateMsg($updateDataUserContract,$template->toArray());

            // 未支付可更新合同时间
            if ($orgContract->step <= UserOrderEnum::STEP_GENERATE_CONTRACT) {
                // 开始时间以提交为准
                $updateDataUserContract['endTime'] = strtotime("+3 years", $updateData['startTime']) - 86400;;
            }

            ChangeSupport::getInstance()->singleUpdate(
                new OpenShopUserContractModel(),
                function ($query) use ($orderNo) {
                    $query->where("orderNo", $orderNo);
                },
                $updateDataUserContract,
                "合同修改",
                OpenShopUserContractModel::getOrderLogTranslate()
            );

            ChangeSupport::getInstance()->batchChangesWriteToOrderLog(
                $orderDetail->id,
                OpenShopSignOrderLogModel::TYPE_ORDER_EDITED,
                getRmsUserInfoByAuth()->username,
                getRmsUserInfoByAuth()->id
            );
//            OpenShopUserContractModel::query()->where('orderNo', $orderNo)->update($updateData->toArray());

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            throw new CustomHttpResponseException(
                ErrCode::errCodeTrans(BaseErrorCode::BASE_CODE_UPDATE_FAIL),
                $e
            );
        }
//        $eventManager->recordCurrent();
//        $eventManager->triggerEvent();
    }

    /**
     * 同步更新合同的加盟政策信息
     * @param array $oldData
     * @param array $template
     * @return array
     */
    public static function updateContractTemplateMsg(array &$oldData,array $template): array
    {
        $oldData['depositAmountRatio']               = $template['depositAmountRatio'];
        $oldData['monthRealAmountCommissionCapping'] = $template['monthRealAmountCommissionCapping'];
        $oldData['isCommissionCapping']              = $template['isCommissionCapping'];
        $oldData['amountCommissionCapping']          = $template['amountCommissionCapping'];
        $oldData['depositAmount']                    = $template['depositAmount'] * $template['shopCount'];
        $oldData['guidanceFee']                      = $template['guidanceFee'] * $template['shopCount'];
        $oldData['decorationDeposit']                = $template['decorationDeposit'] * $template['shopCount'];
        $oldData['managementCostEveryYear']          = $template['managementCostEveryYear'] * $template['shopCount'];
        $oldData['managementCost']                   = $template['managementCost'] * $template['shopCount'];
        $oldData['deposit']                          = $template['deposit'] * $template['shopCount'];
        $oldData['technologyTransferFee']            = $template['technologyTransferFee'] * $template['shopCount'];
        $oldData['initialFee']                       = $template['initialFee'] * $template['shopCount'];
        $oldData['shopCount']                        = $template['shopCount'];
        // 分账模式下 contractType 固定为 9
        $oldData['contractType']                     = $template['mode'] == OpenShopContractTemplateModel::MODE_2 ? UserContractEnum::CONTRACT_TYPE_9 : $oldData['contractType'];

        return $oldData;
    }


    /**
     * @param string $orderNo
     * @return array
     */
    public static function detail(string $orderNo): array
    {
        try {
            return [
                'orderDetail' => OrderDetailResource::collection(OpenShopSignOrderModel::orderDetail($orderNo))
                                                    ->getIterator()->current(),
                'contract'    => UserContractResource::collection(
                    [OpenShopUserContractModel::query()->with('templateRel')
                                              ->where('orderNo', $orderNo)->orderBy("id", "desc")->first()]
                )->getIterator()->current()
            ];
        } catch (Exception $exception) {
            throw new CustomHttpResponseException(
                ErrCode::errCodeTrans(BaseErrorCode::BASE_CODE_DETAIL_FAIL),
                $exception
            );
        }
    }

    /**
     * 处理错误异常信息
     *
     * @param object $rmsUser
     * @param string $orderNo
     * @throws Exception
     */
    public static function handleExceptionMsg(object $rmsUser, string $orderNo)
    {
        try {
            DB::beginTransaction();

            $userContract = OpenShopUserContractModel::query()->where("orderNo", $orderNo)->first();
            if (empty($userContract) || empty($userContract->exceptionMsg)) {
                throw new ResponseHttpException(\App\Enums\BaseErrorCode::$UN_SUPPORT_OPERATION);
            }

            OpenShopUserContractModel::query()
                                     ->where("orderNo", $orderNo)
                                     ->update([
                                         "exceptionMsg" => null,
                                         "updatedAt"    => time(),
                                         "updatedByUid" => $rmsUser->id
                                     ]);

            OpenShopSignOrderLogModel::logInsert(
                OpenShopSignOrderModel::query()->where("orderNo", $orderNo)->first()->id,
                OpenShopSignOrderLogModel::CONTRACT_EXCEPTION_HANDLE,
                $rmsUser->username,
                $rmsUser->id
            );

            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            handleException($exception);
        }
    }

    /**
     * @param string $orderNo
     * @return array|void
     * @throws Exception
     */
    public static function generateUserContract(string $orderNo)
    {
        try {
            $userContract = OpenShopUserContractModel::query()
                                                     ->whereIn("contractType",
                                                        OpenShopUserContractModel::OPEN_SHOP_CONTRACT_GROUP)
                                                     ->where("orderNo", $orderNo)
                                                     ->orderBy("id", "desc")
                                                     ->first();

            if (
                !empty($userContract)
                &&
                empty($userContract->exceptionMsg)
                &&
                OpenShopUserExtContractModel::query()->where("contractId", $userContract->id)->get()->isEmpty()
                &&
                $userContract->contractStatus == OpenShopUserContractModel::CONTRACT_STATUS_NORMAL
                &&
                OpenShopSignOrderModel::query()->where("orderNo", $orderNo)->first()->step >= SignOrderEnum::STEP_4
            ) {
                $exceptionMsg = UserExtContractService::orderNotify($orderNo);
                if (!empty($exceptionMsg)) {
                    throw new ResponseHttpException(\App\Enums\BaseErrorCode::$USER_CONTRACT_GENERATE_FAIL);
                }
            } else {
                throw new ResponseHttpException(\App\Enums\BaseErrorCode::$USER_CONTRACT_HAS_EXISTS_OR_NOT_SUPPORT);
            }

            return [
                "signUrl" => UserExtContractService::$signUrl
            ];
        } catch (Exception $exception) {
            handleException($exception);
        }
    }

    /**
     * 获取订单合同中的年管理费
     * @param string $orderNo
     * @return int
     */
    public static function getManagementCostEveryYear(string $orderNo): int
    {
        $mainProcess = OpenShopMainProcessModel::query()->where('orderNo', $orderNo)->first();
        if (!$mainProcess) {
            return 0;
        }

        if ($mainProcess->childOrder == MainProcessEnum::CHILD_ORDER_1) {

            // 子订单
            $pOrderNo = $mainProcess->parentOrdersRel->orderNo;
        } else {

            // 主订单
            $pOrderNo = $orderNo;
        }

        // 主订单的金额
        $userContract = OpenShopUserContractModel::query()
                                                 ->where('orderNo', $pOrderNo)
                                                 ->first();
        if (!$userContract || $userContract->shopCount == 0) {
            return FeeEnum::FEE_MANAGE;
        }

        // 分账模式
        if ($userContract->depositAmountRatio > 0) {
            return 0;
        }

        $pPrice = $userContract->managementCostEveryYear;
        $shopCount = $userContract->shopCount;

        return (int)($pPrice / $shopCount);
    }

    /**
     * 合同作废
     *
     * @param string $orderNo
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface|ValidationException
     */
    public static function invalidContract(string $orderNo)
    {
        try {
            $userContract = OpenShopUserContractModel::query()
                                                     ->with(["signOrderRel", "userExtContractRel"])
                                                     ->whereIn("contractType",
                                                         OpenShopUserContractModel::OPEN_SHOP_CONTRACT_GROUP)
                                                     ->where("orderNo", $orderNo)
                                                     ->orderBy("id", "desc")
                                                     ->first();

            OpenShopUserContractModel::copyRow($orderNo);
            $update = [
                "invalidedTime"  => time(),
                "invalidedUid"   => getRmsUserInfoByAuth()->id,
                "contractStatus" => OpenShopUserContractModel::CONTRACT_STATUS_INVALID
            ];

            if (
                $userContract->userExtContractRel
                &&
                $userContract->signTime > 0
                &&
                $userContract->contractStatus == ContractStatusEnum::COMPLETE
            ) {
                //已签署
                $logType = OpenShopSignOrderLogModel::INVALID_USER_CONTRACT_WITH_SIGN;
            } else {
                //待签署
                $logType = OpenShopSignOrderLogModel::INVALID_USER_CONTRACT_WITHOUT_SIGN;
                UserExtContractService::invalidContract($userContract->contractExtNo);
                $update = array_merge($update, ["isDeleted" => 1]);

//                //契约锁合同更新签约信息
//                OpenShopUserExtContractModel::query()->where("contractId", $userContract->id)->update([
//                    "signStatus" => 1,
//                    "signTime"   => time()
//                ]);
            }

            //合同数据回写
            $userContract->setRawAttributes($update)->save();

            //添加作废日志
            OpenShopSignOrderLogModel::logInsert(
                $userContract->signOrderRel->id,
                $logType,
                getRmsUserInfoByAuth()->username ?? '',
                getRmsUserInfoByAuth()->id ?? 0
            );

            //更新订单合同状态
            OpenShopSignOrderModel::query()->where("orderNo", $orderNo)
                                  ->update(["contractStatus" => OpenShopSignOrderModel::CONTRACT_STATUS_CHANGE]);

        } catch (Exception $exception) {
            handleException($exception, ContractErrCode::$ERR_INVALID_CONTRACT_FAIL);
        }
    }

    /**
     * 合同催签
     *
     * @param object $params
     * @throws ValidationException|Exception
     */
    public static function contractNotice(object $params)
    {
        try {
            $workflowOrder = WorkflowOrderModel::query()->where("workflowNo", $params->workflowNo)->first();
            $existsCount   = WorkflowOrderNodeModel::query()
                                                   ->where("workflowOrderId", $workflowOrder->id)
                                                   ->where('status', WorkflowOrderNodeModel::STATUS_ING)
                                                   ->where('businessType', WorkflowEnum::BUSINESS_TYPE_RENEW_SIGN)
                                                   ->count();
            if (!$existsCount) {
                throw new KfHttpResponseException(RenewError::STATUS_ERROR_NOT_FOR_SIGNING);
            }
            $userRenewContract = OpenShopUserContractModel::query()
                                                          ->where("workflowNo", $params->workflowNo)
                                                          ->where("contractType", UserContractEnum::CONTRACT_TYPE_8)
                                                          ->where("signTime", 0)
                                                          ->orderBy("id", "desc")
                                                          ->first();

            if (empty($userRenewContract)) {
                throw new KfHttpResponseException(RenewError::RENEW_USER_CONTRACT_NOT_EXISTS);
            }
            UserExtContractService::contractNotice($userRenewContract->contractExtNo);
        } catch (Exception $exception) {
            handleKfException($exception, BaseError::SERVER_INTERNAL_ERROR, func_get_args());
        }
    }

    /**
     * 获取剩余待支付的加盟费
     * @param string $orderNo
     * @param OpenShopSignOrderModel $signOrderModel
     * @return array
     * @throws Exception
     */
    public static function getLastPrice(OpenShopSignOrderModel $signOrderModel): array
    {
        $orderNo = $signOrderModel->orderNo;

        // 获取合同模式
        $contractModel = $signOrderModel->contractRel;
        if (!$contractModel) {
            BuildFs::newRobot(SendFs::ROBOT_WARNING)
                   ->setTitleContent("支付加盟费，未找到店铺合同", "orderNo:{$orderNo}")
                   ->send();

            return [true, 0, 0];
        }

        $depositAmount = $contractModel->depositAmount; // 定金金额

        // 应付金额
        $lastPrice = $signOrderModel->shouldPayPrice - $signOrderModel->payPrice;
        $isFinalPay = true; // 是否尾款

        // 定金模式特殊处理
        if ($contractModel->mode == OpenShopContractTemplateModel::MODE_3) {

            // 根据阶段来判断应付金额
            $nowStepStatus = (int)OpenShopMainProcessModel::query()
                                                          ->where('orderNo', $orderNo)
                                                          ->orderByDesc('id')
                                                          ->value('nowStepStatus');

            $nowStepStatusSort = MissionTemplateService::getSortByStepStatus($nowStepStatus);

            // 第一次支付定金
            if ($nowStepStatusSort <= MissionTemplateService::getSortByStepStatus(MissionTemplateEnum::STEP_STATUS_2)) {

                // 应付金额 = 定金金额
                $lastPrice = $depositAmount - $signOrderModel->payPrice;
                $isFinalPay = false;
            } else {

                // 第二次支付尾款 - 无需特殊处理
            }
        }

        if ($lastPrice < 0) {
            $lastPrice = 0;
        }

        return [$isFinalPay, $lastPrice, $depositAmount];
    }
}
